#include "my_service.pb.h"
#include "xlcomm/base/logger.h"
#include "xlcomm/net/event_loop_thread.h"
#include "xlcomm/net/protorpc/rpc_channel_client.h"
using namespace xlcomm;

void AddCallback(AddReuest* add, AddResponse* add_res) {
  LOG_DEBUG << __FUNCTION__ << "==== a:" << add->a() << " b:" << add->b();
  LOG_DEBUG << __FUNCTION__ << "==== add_res: " << add_res->result();
}

void EchoCallback(EchoResponse* echo_res) {
  LOG_DEBUG << __FUNCTION__ << "==== echo_res: " << echo_res->msg();
}

void QueryPersonCallback(PersonResponse* person_res) {
  LOG_DEBUG << __FUNCTION__ << "==== name: " << person_res->name()
            << " age:" << person_res->age();
}

int main() {
  Logger::SetLogLevel(Logger::kDebug);

  net::EventLoopThread loop_thread;
  net::EventLoop* loop = loop_thread.StartLoop();
  net::RpcChannelClient client(loop, net::InetAddress(40001, "127.0.0.1"));
  client.Connect();

  std::this_thread::sleep_for(std::chrono::seconds(1));

  MyService_Stub stub(&client);
  AddReuest add;
  add.set_a(1);
  add.set_b(2);
  AddResponse add_res;
  LOG_DEBUG << "rpc_client_test==== a:" << add.a() << " b:" << add.b();
  stub.Add(NULL, &add, &add_res,
           google::protobuf::NewCallback(&AddCallback, &add, &add_res));

  EchoRequest echo;
  echo.set_msg("hello rpc");
  EchoResponse echo_res;
  stub.Echo(NULL, &echo, &echo_res,
            google::protobuf::NewCallback(&EchoCallback, &echo_res));

  PersonRequest person;
  person.set_name("LiMing");
  person.set_age(30);
  PersonResponse person_res;
  stub.QueryPerson(
      NULL, &person, &person_res,
      google::protobuf::NewCallback(&QueryPersonCallback, &person_res));

  std::this_thread::sleep_for(std::chrono::seconds(2));
  client.Disconnect();
  std::this_thread::sleep_for(std::chrono::seconds(1));
}